<template>
  <div class="contracting-manager" ref="contracting">
    <div class="contracting-container">
      <div class="filter-container">
        <el-form :model="tableParams" label-width="80">
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="客户信息">
                <el-input placeholder="请输入姓名/手机号/小区名称" v-model="tableParams.customerInfo" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="承包人">
                <el-input placeholder="请输入" v-model="tableParams.jobUserName" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发包方式">
                <el-select placeholder="请选择" v-model="tableParams.contracteesType">
                  <el-option label="按清单发包" :value="1" />
                  <el-option label="按面积发包" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <div class="filter-container-buttons">
                <el-button type="primary" :icon="Search" @click="handelSearch">查询</el-button>
                <el-button type="primary" plain :icon="RefreshRight" @click="handelResetFilter">重置</el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="tabs-sticky">
        <div class="tabs-content">
          <el-tabs class="demo-tabs" v-model="tableParams.state" @tab-change="handleTabsChange">
            <el-tab-pane name="" label="全部">
              <template #label>
                <span class="custom-tabs-label">
                  <span>全部</span>
                  <span v-if="sunCount"> ({{ sunCount }}) </span>
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane :name="1">
              <template #label>
                <span class="custom-tabs-label">
                  <span>未发包</span>
                  <span v-if="countData.find(item => item.state === 1)?.num">
                    ({{ countData.find(item => item.state === 1)?.num }})
                  </span>
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane :name="2">
              <template #label>
                <span class="custom-tabs-label">
                  <span>待提交申请</span>
                  <span v-if="countData.find(item => item.state === 2)?.num">
                    ({{ countData.find(item => item.state === 2)?.num }})
                  </span>
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane :name="3">
              <template #label>
                <span class="custom-tabs-label">
                  <span>待审核</span>
                  <span v-if="countData.find(item => item.state === 3)?.num">
                    ({{ countData.find(item => item.state === 3)?.num }})
                  </span>
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane :name="4">
              <template #label>
                <span class="custom-tabs-label">
                  <span>已发包</span>
                  <span v-if="countData.find(item => item.state === 4)?.num">
                    ({{ countData.find(item => item.state === 4)?.num }})
                  </span>
                </span>
              </template>
            </el-tab-pane>
            <el-tab-pane :name="5">
              <template #label>
                <span class="custom-tabs-label">
                  <span>审核拒绝</span>
                  <span v-if="countData.find(item => item.state === 5)?.num">
                    ({{ countData.find(item => item.state === 5)?.num }})
                  </span>
                </span>
              </template>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <div class="table-container" element-loading-text="数据加载中..." v-loading="isLoadingTable">
        <el-table
          ref="reformTableRef"
          :data="tableData"
          stripe
          border
          style="width: 100%"
          :header-cell-style="{ background: '#F2F6FC', color: '#4E5969', 'font-weight': 400, 'font-size': '14px' }"
          row-key="reformId"
          :height="tableHeight"
        >
          <el-table-column prop="customerName" label="客户" show-overflow-tooltip  width="250">
            <template #default="{row}">
              {{row.customerName}} | {{ row.address}}
            </template>
          </el-table-column>
          <el-table-column prop="customerName" label="发包状态" show-overflow-tooltip width="180">
            <template #default="{ row }">
              <span class="status" :class="`status-${statusLabel(row).value[0]}`">
                {{ statusLabel(row).value[1] }}
              </span>
              <span style="margin-left: 10px; color: #ffa73b">{{
                [2, 4].includes(row.approvalType) ? "编辑审核中" : row.approvalType === 3 ? "删除审核中" : ""
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="" label="发包明细" show-overflow-tooltip width="100">
            <template #default="{ row }">
              <span v-if="row.state !== 1" style="color: #007dff; cursor: pointer" @click="handleDetails(row)">查看明细</span>
            </template>
          </el-table-column>
          <el-table-column prop="customerName" label="发包方式" show-overflow-tooltip width="100">
            <template #default="{ row }">
              {{ typeData[row.contracteesType] }}
            </template>
          </el-table-column>
          <el-table-column prop="jobUserName" label="承包人" show-overflow-tooltip width="100" />
          <el-table-column prop="factMoney" label="实际发包金额" show-overflow-tooltip />
          <el-table-column prop="listNum" label="发包清单项" show-overflow-tooltip />
          <el-table-column prop="listMoneyTotal" label="发包清单合计" show-overflow-tooltip width="150" />
          <el-table-column prop="contractHourseArea" label="合同面积" show-overflow-tooltip width="100" />
          <el-table-column prop="auxiliaryMoneyMax" label="辅料金额上限" show-overflow-tooltip />
          <el-table-column prop="contracteesDate" label="发包时间" show-overflow-tooltip width="150" />
          <el-table-column label="操作" width="140" fixed="right" align="center">
            <template #default="{ row }">
              <div class="table-operate" v-if="row.assignBlameState !== 11 && row.reformState !== 6">
                <el-button v-for="button in getVisibleButtons(row)" :key="button.text" type="primary" link @click="button.action">
                  {{ button.text }}
                </el-button>
                <div v-if="showDropdownItem(row)">
                  <el-dropdown>
                    <span class="el-dropdown-link"
                      >展开
                      <el-icon class="el-icon--left">
                        <arrow-down />
                      </el-icon>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          v-for="item in filteredDropdownItems(row)"
                          :key="item.command"
                          :command="item.command"
                          @click="item.action"
                        >
                          <el-button type="primary" style="height: 22px" link>{{ item.text }}</el-button>
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <custom-pagination
      v-if="tableData.length > 0"
      :total="listTotal"
      v-model:limit="tableParams.size"
      v-model:page="tableParams.current"
      layout="total, slot, prev, pager, next, jumper"
      @pagination="handelPage"
    >
    </custom-pagination>
    <!--  发包  -->
    <AddDrawer ref="addDrawer" @handelSearch="handelSearch" @handleDetails="handleDetails" />
    <!--  删除  -->
    <DelModal ref="delModal" @handelSearch="handelSearch" />
    <!--  附件管理  -->
    <FileTable ref="fileTable" />
    <!--  付款计划   -->
    <PayDrawer ref="payDrawer" @handelSearch="handelSearch" />
    <!--  付款计划详情  -->
    <PayDrawerDetails ref="payDrawerDetails" />
    <!--  发包明细  -->
    <PackageDetails ref="packageDetails" @handelSearch="handelSearch" />
  </div>
</template>

<script setup>
import { nextTick, ref } from "vue";
import { ArrowDown, RefreshRight, Search } from "@element-plus/icons-vue";
import { statusMapList, typeData } from "@/views/contractingManagement/list/config";
import useComputedParams from "@/hooks/useComputedParams";
import AddDrawer from "@/views/contractingManagement/list/components/addDrawer/index.vue";
import DelModal from "@/views/contractingManagement/list/components/delModal/index.vue";
import FileTable from "@/views/contractingManagement/list/components/fileTable/index.vue";
import PayDrawer from "@/views/contractingManagement/list/components/payDrawer/index.vue";
import PayDrawerDetails from "@/views/contractingManagement/list/components/payDrawer/details.vue";
import PackageDetails from "@/views/contractingManagement/list/components/packageDetails/index.vue";
import { cancelApproval, contractList, numbers } from "@/apis/contracting";
import { setCache } from "@/utils/cache";
import { deepCopy } from "ali-oss/lib/common/utils/deepCopy";
import { ElMessage, ElMessageBox } from "element-plus";

const isLoadingTable = ref(false);
const tableHeight = ref(100);
const contracting = ref();
const countData = ref([]);
const addDrawer = ref();
const delModal = ref();
const fileTable = ref();
const payDrawer = ref();
const payDrawerDetails = ref();
const sunCount = ref();
const packageDetails = ref();
const initTableParams = {
  current: 1,
  size: 10,
  state: ""
};
const tableParams = ref({ ...initTableParams });
const tableData = ref([]);
const listTotal = ref(0);
// 选择售后状态
const handleTabsChange = e => {
  tableParams.value.state = e;
  handelSearch();
};
const buttons = row => {
  return [
    {
      command: 0,
      condition: () => row.state === 1,
      text: "发包",
      action: () => handelAdd(row)
    },
    {
      command: 1,
      condition: () => [2].includes(row.state),
      text: "提交申请",
      action: () => handelOperate(row, 1)
    },
    {
      command: 2,
      condition: () => [5].includes(row.state),
      text: "重新申请",
      action: () => handelOperate(row, 2)
    },
    {
      command: 3,
      condition: () => [3, 4].includes(row.state),
      text: "付款计划",
      action: () => handelOperate(row, 3)
    },
    {
      command: 4,
      condition: () => [2, 3, 4, 5].includes(row.state),
      text: "附件管理",
      action: () => handelOperate(row, 4)
    },
    {
      command: 5,
      condition: () => [4].includes(row.state),
      text: "编辑",
      action: () => handelOperate(row, 5)
    },
    {
      command: 6,
      condition: () => [2, 3, 4, 5].includes(row.state),
      text: "删除",
      action: () => handelOperate(row, 6)
    },
    {
      command: 7,
      condition: () => [3].includes(row.state),
      text: "撤回申请",
      action: () => handelOperate(row, 7)
    }
  ];
};
//定义按钮
const getVisibleButtons = row => {
  // 过滤可见按钮
  const filteredButtons = buttons(row).filter(btn => btn.condition());
  return filteredButtons.length <= 2 ? filteredButtons : [filteredButtons[0]];
};
//判断按钮显示个数是否大于2 大于2返回true
const showDropdownItem = row => {
  const buttonCount = buttons(row).reduce((count, item) => count + item.condition(), 0);
  return buttonCount > 2;
};
// 过滤掉第一个满足条件的下拉项
const filteredDropdownItems = row => {
  const visibleItems = buttons(row).filter(item => item.condition());
  visibleItems.shift();
  return visibleItems;
};
// 发包状态
const statusLabel = useComputedParams(data => {
  return statusMapList.has(data.state) ? statusMapList.get(data.state) : ["danger", "未知"];
});
// 获取列表数据
const getList = async () => {
  isLoadingTable.value = true;
  const { data } = await contractList(tableParams.value);
  tableData.value = data.list;
  listTotal.value = data.total;
  isLoadingTable.value = false;
  await getNumbers();
};
const getNumbers = async () => {
  const { data } = await numbers(tableParams.value);
  countData.value = data;
  let num = 0;
  data.map(item => {
    num += item.num;
  });
  sunCount.value = num || null;
};
const setHeight = () => {
  nextTick(() => {
    tableHeight.value = document.documentElement.clientHeight - 420;
    console.log(tableHeight.value);
  });
};
// 分页查询
const handelPage = () => {
  tableData.value = [];
  getList();
};
// 操作
const handelOperate = (row, i) => {
  switch (i) {
    case 1:
      addDrawer.value.openEdit(row, "去确认发包项", "提交");
      break;
    case 2:
      addDrawer.value.openEdit(row, "去确认发包项", "提交");
      break;
    case 3:
      if (row.setPaymentPlan) {
        payDrawerDetails.value.openDrawer(row);
      } else {
        payDrawer.value.openDrawer(row);
      }
      break;
    case 4:
      fileTable.value.openModal(row.contracteesId);
      break;
    case 5:
      addDrawer.value.openEdit(row, "提交", "编辑");
      break;
    case 6:
      delModal.value.openModal(row);
      break;
    case 7:
      ElMessageBox.confirm("你确定要撤回申请吗？", "撤回申请", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        center: true,
        customClass: "message-box",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            console.log(row);
            await cancelApproval(row.contracteesId);
            ElMessage.success("撤回成功");
            getList();
            done();
          } else {
            done();
          }
        }
      });
      break;
  }
};
// 查看明细
const handleDetails = row => {
  let code = deepCopy(Math.random().toString().slice(2, 8));
  setCache("randomCode", code);
  packageDetails.value.openDrawer(row);
};

// 新增发包
const handelAdd = row => {
  addDrawer.value.openAdd(row);
};
/**
 * 过滤
 */
const handelSearch = () => {
  tableParams.value.current = 1;
  getList();
};

// 重置
const handelResetFilter = () => {
  tableParams.value = { ...initTableParams };
  handelSearch();
};
getList();
setHeight();
</script>

<style scoped lang="scss">
@use "index";
</style>
